<script setup>
import { ref } from 'vue'
import { useDropZone, useClipboard } from '@vueuse/core'
import { UploadFilled } from '@element-plus/icons-vue'
import { useConfigStore } from '@renderer/store/config.js'
import { uploadImage } from '@renderer/api/gitee.js'
const configStore = useConfigStore()

const { config } = configStore
const dropZoneRef = ref()
const filesData = ref([])
function onDrop(files) {
  filesData.value = []
  if (files) {
    filesData.value = files.map((item) => {
      return { file: item }
    })
  }
}

useDropZone(dropZoneRef, onDrop)

function handleImageUpload(file) {
  return new Promise((resolve, reject) => {
    if (file && file instanceof Blob) {
      const reader = new FileReader()
      reader.onloadend = function () {
        const base64String = reader.result // 读取完成后得到Base64字符串

        if (base64String) {
          //console.log('Base64编码结果：', base64String)
          // 这里可以进行其他操作或发送到服务器等处理
          resolve(base64String.substring(base64String.indexOf(',') + 1))
        } else {
          reject('Base64编码失败')
        }
      }

      reader.readAsDataURL(file) // 开始读取文件内容并转换为Base64格式
    } else {
      console.error('无效的文件类型')
      reject('无效的文件类型')
    }
  })
}

const uploadFile = () => {
  let arr = filesData.value.map((item) => {
    return httpRequest(item.file)
  })
  Promise.all(arr).then((res) => {
    res.forEach((item, i) => {
      filesData.value[i].response = item
    })
  })
}
const httpRequest = async (file) => {
  console.log('🚀 ~ file: upLoad.vue:58 ~ httpRequest ~ file:', file)
  try {
    const formData = new FormData()
    // const filename = new Date().getTime()
    // const renameFile = new File([file.raw], filename, {
    //   type: 'image/jpeg',
    //   lastModified: Date.now()
    // })
    let base64Data = await handleImageUpload(file)
    formData.append('content', base64Data)
    formData.append('access_token', config.accessToken)
    formData.append('message', '上传图片')
    let content = await uploadImage(config, formData, file.name)
    content.markdown = `![${content.name}](${content.download_url})`
    return content
  } catch (error) {
    return error
  }
}

const { copy } = useClipboard()
</script>
<template>
  <div
    ref="dropZoneRef"
    class="border bg-gray-400/10 min-h-[200px] rounded h-auto flex flex-col mt-6"
  >
    <div
      class="flex flex-col flex-1 justify-center items-center text-gray-400 font-bold mb-2 text-[10vw]"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <span class="text-base">将图片/文件夹拖拽到此处</span>
    </div>
  </div>
  <div class="my-2 flex justify-center">
    <el-button type="primary" size="large" class="w-full" @click="uploadFile">点击选择</el-button>
    <el-button type="primary" size="large" class="w-full" @click="uploadFile">提交文件</el-button>
  </div>

  <div class="flex flex-wrap flex-col">
    <div v-for="(item, index) in filesData" :key="index" class="break-all mb-2 bg-gray-400/10 p-2">
      <p>Name: {{ item.file.name }}</p>
      <p>Size: {{ item.file.size }}</p>
      <p>Type: {{ item.file.type }}</p>
      <p>Last modified: {{ item.file.lastModified }}</p>
      <div v-if="item.response" class="flex">
        <div class="flex-1">上传结果：{{ item.response?.message || '上传成功' }}</div>
        <template v-if="!item.response?.message">
          <el-button type="warning" size="small" @click="copy(item.response.download_url)"
            >复制图片链接</el-button
          >
          <el-button type="warning" size="small" @click="copy(item.response.markdown)"
            >复制markdown格式</el-button
          >
        </template>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped></style>
